package com.shuosen.gmall.payment.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.shuosen.gmall.bean.PaymentInfo;
import com.shuosen.gmall.bean.enums.PaymentStatus;
import com.shuosen.gmall.config.ActiveMQUtil;
import com.shuosen.gmall.payment.mapper.PaymentMapper;
import com.shuosen.gmall.service.PaymentService;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.ExampleMapper;
import tk.mybatis.mapper.entity.Example;

import javax.jms.*;
import java.util.Date;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
  private PaymentMapper  paymentMapper  ;

  @Autowired
  private ActiveMQUtil activeMQUtil  ;

  @Autowired
  private  AlipayClient  alipayClient ;

    @Override
    public void savePaymentInfo(PaymentInfo paymentInfo) {
        //完成保存数据的操作
        paymentMapper.insertSelective(paymentInfo);
    }

    @Override
    public PaymentInfo getPaymentInfo(PaymentInfo paymentInfo) {

        return paymentMapper.selectOne(paymentInfo);
    }

    @Override
    public void updatePaymentInfo(String out_trade_no, PaymentInfo paymentInfoUpd) {
        Example example = new Example(PaymentInfo.class);
        example.createCriteria().andEqualTo("outTradeNo",out_trade_no);
        paymentMapper.updateByExampleSelective(paymentInfoUpd,example);
    }

    @Override
    public void sendPaymentResult(PaymentInfo paymentInfo, String result) {
        //发送消息
        Connection connection = activeMQUtil.getConnection();
        try {
            connection.start();
            Session session = connection.createSession(true,Session.SESSION_TRANSACTED);
            Queue payment_result_queue = session.createQueue("PAYMENT_RESULT_QUEUE");
            MessageProducer producer = session.createProducer(payment_result_queue);
            //创建消息发送
            ActiveMQMapMessage activeMQMapMessage = new ActiveMQMapMessage();
            activeMQMapMessage.setString("orderId",paymentInfo.getOrderId());
            activeMQMapMessage.setString("result",result);
            producer.send(activeMQMapMessage);
            session.commit();
            producer.close();

            session.close();
            connection.close();


        } catch (JMSException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean checkPayment(PaymentInfo paymentInfo) {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\""+paymentInfo.getOutTradeNo()+"\"" +
                "  }");
        AlipayTradeQueryResponse response = null;
        try {
             response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //在支付宝中有交易记录
        if (response.isSuccess()) {
            if ("TRADE_SUCCESS".equals(response.getTradeStatus())||"TRADE_FINISHED".equals(response.getTradeStatus())){
                PaymentInfo paymentInfoUpd = new PaymentInfo();
                //设置状态
                paymentInfoUpd.setPaymentStatus(PaymentStatus.PAID);
                //设置创建时间
                paymentInfoUpd.setCallbackTime(new Date());
                //设置内容
                updatePaymentInfo(paymentInfo.getOutTradeNo(),paymentInfoUpd);

                //支付模块发送通知给订单，说明支付已经完成
               sendPaymentResult(paymentInfo,"success");
                return true;
            }
            System.out.println("调用成功");
        }
        return false;

    }

    /**
     *
     * @param outTradeNo  第三方交易编号
     * @param delaySec   设置查询的时间
     * @param checkCount   设置查询的次数
     */
    @Override
    public void sendDelayPaymentResult(String outTradeNo, int delaySec, int checkCount) {
        //发送消息 第三方交易编号  ,查询的时间   查询的次数
        Connection connection = activeMQUtil.getConnection();
        try {
            connection.start();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            //创建队列

            Queue payment_result_check_queue = session.createQueue("PAYMENT_RESULT_CHECK_QUEUE");
            MessageProducer producer = session.createProducer(payment_result_check_queue);
            ActiveMQMapMessage activeMQMapMessage = new ActiveMQMapMessage();
            activeMQMapMessage.setString("orderTradeNo",outTradeNo);
            activeMQMapMessage.setInt("delaySec",delaySec);
            activeMQMapMessage.setInt("checkCount",checkCount);
            producer.send(activeMQMapMessage);
            //设置一下延迟队列
            activeMQMapMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,delaySec*1000);

            //提交数据
            producer.send(activeMQMapMessage);
            session.commit();
            producer.close();
            session.close();
            connection.close();


        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void closePayment(String id) {
        Example example = new Example(PaymentInfo.class);
        example.createCriteria().andEqualTo("orderId",id);
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatus.ClOSED);
        paymentMapper.updateByExampleSelective(paymentInfo, example);
    }
}
